import { getCurrentUser, getMenus } from '@/api/auth'
import modules /**@type {Map} */ from '@/config.js'
import LayOut from '@/layout/index.vue'
import router from '@/router/index.js'
function filterMenus(menus, desMenus) {
    for (let menu of menus) {
        if (menu.url) {
            let desMenu = { ...menu }
            delete desMenu.children
            desMenus.push(desMenu)
            if (menu.children?.length > 0) {
                desMenu.children = []
                filterMenus(menu.children, desMenu.children)
                if (desMenu.children.length == 0) {
                    delete desMenu.children
                }
            }
        }
    }
}

function getComponent(url, com) {
    return (resolve) => {
        let res
        if (modules.has(url)) {
            res = require([`@/views${url}/${com}`], resolve)
        } else {
            res = require(['@/views/error-page/404.vue'], resolve)
        }
        return res
    }
}

function buildRoute(menus, routes, parentUrl) {
    for (let item of menus) {
        let obj
        if (parentUrl) {
            const mainUrl = `/${parentUrl}/${item.url}`
            obj = {
                path: item.url,
                component: getComponent(mainUrl, 'index.vue'),
                name: item.menuname,
                meta: {
                    menuname: item.menuname,
                    menupath: mainUrl
                }
            }
            if (modules.has(mainUrl)) {
                let coms = modules.get(mainUrl)
                coms.forEach((com) => {
                    routes.push({
                        path: `${item.url}/${com}`,
                        component: getComponent(mainUrl, com + '.vue'),
                        meta: {
                            menuname: item.menuname,
                            menupath: mainUrl
                        }
                    })
                })
            }
        } else {
            obj = {
                path: '/' + item.url,
                component: LayOut,
                name: item.menuname,
                meta: {
                    menuname: item.menuname,
                    menupath: '/' + item.url
                }
            }
        }
        if (item.children) {
            obj.children = []
        }
        routes.push(obj)
        if (item.children) {
            buildRoute(item.children, obj.children, item.url)
        }
    }
}

export default {
    namespaced: true,
    state: {
        id: null,
        username: '',
        role: '',
        functionId: [],
        headImg: ''
    },
    mutations: {
        SET_USER: (state, user) => {
            for (let key in state) {
                if (user?.hasOwnProperty(key)) {
                    state[key] = user[key]
                }
            }
        },
        SET_FUNCTIONID: (state, { functionIds }) => {
            state.functionIds = functionIds.split(',')
        }
    },
    actions: {
        getLoginInfo({ state, commit, dispatch, rootState }) {
            return getCurrentUser().then((data) => {
                if (!data.data?.id) {
                    return Promise.reject({ msg: '登录超时' })
                }
                commit('SET_USER', data.data)
                dispatch('setUserInfo', data.data)
            })
        },
        setUserInfo({ state, commit, rootState }, userData) {
            commit('SET_USER', userData)
            return getMenus(userData.id).then((data) => {
                commit('SET_FUNCTIONID', data.data)
                let desMenus = new Array()
                filterMenus(data.data.menus, desMenus)
                let asyncRoute = new Array()
                buildRoute(desMenus, asyncRoute)
                commit('menus/SET_MENUS', data.data, { root: true })
                router.addRoutes(asyncRoute)
                return true
            })
        }
    }
}
